package com.ironmaking.Utils;

import com.ironmaking.Vo.results.PageResult;
import org.springframework.data.domain.Page;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 分页工具
 */
public class PageUtil extends cn.hutool.core.util.PageUtil {

    /**
     * List 分页
     */
    public static List toPage(int page, int size , List list) {
        page-=1;
        int fromIndex = page * size;
        int toIndex = page * size + size;
        if(fromIndex > list.size()){
//            return new ArrayList();
            return null;
        } else if(toIndex >= list.size()) {
            return list.subList(fromIndex,list.size());
        } else {
            return list.subList(fromIndex,toIndex);
        }
    }



    /**
     * List 分页
     */
    public static PageResult toPageResult(int page, int size , List list) {
        PageResult result = new PageResult();
        result.setPage(page);
        result.setSize(size);
        result.setTotal(list.size());
        int fromIndex = page * size;
        int toIndex = page * size + size;
        if (list.size() <= 0) {
            return null;
        } else if(fromIndex > list.size()){
            result.setCurrent(0);
            result.setObject(null);
            return result;
        } else if(toIndex >= list.size()) {
            result.setCurrent(list.size() - fromIndex);
            result.setObject(list.subList(fromIndex,list.size()));
            return result;
        } else {
            result.setCurrent(size);
            result.setObject(list.subList(fromIndex,toIndex));
            return result;
        }
    }

    /**
     * Page 数据处理，预防redis反序列化报错
     */
    public static Map<String,Object> toPage(Page page) {
        Map<String,Object> map = new LinkedHashMap<>(2);
        map.put("content",page.getContent());
        map.put("totalElements",page.getTotalElements());
        return map;
    }

    /**
     * 自定义分页
     */
    public static Map<String,Object> toPage(Object object, Object totalElements) {
        Map<String,Object> map = new LinkedHashMap<>(2);
        map.put("content",object);
        map.put("totalElements",totalElements);
        return map;
    }

}
